package com.zhilei.controller;

import com.google.gson.Gson;
import com.zhilei.base.BaseInfoProperties;
import com.zhilei.grace.result.GraceJSONResult;
import com.zhilei.grace.result.ResponseStatusEnum;
import com.zhilei.intercept.JWTCurrentUserInterceptor;
import com.zhilei.pojo.Admin;
import com.zhilei.pojo.bo.AdminBO;
import com.zhilei.pojo.vo.AdminVO;
import com.zhilei.service.AdminService;
import com.zhilei.untils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 接收前端请求的数据的请求体，使用 @RequestBody 这会将请求的正文，就是请求的JSON转换为Java对象
 * 返回给前端数据，也就是将数据写入到JSON中发送给前端，使用 @ResponseBody
 *
 * @author zhilei
 * @data 2024-09-05
 */
@RestController
@RequestMapping("admin")
@Slf4j
public class AdminController extends BaseInfoProperties {

    @Autowired
    private JWTUtils jwtUtils;

    @Autowired
    private AdminService adminService;

    /**
     * @return
     */
    @PostMapping("login")
    public GraceJSONResult login(@Validated @RequestBody AdminBO adminBO) {

        // TODO 1. 查询用户是否存在
        boolean isExist = adminService.adminLogin(adminBO);

        // TODO 2. 对查询的用户进行校验
        if (!isExist) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.ADMIN_LOGIN_ERROR);
        }

        // TODO 3. 查询用户信息
        Admin admin = adminService.getAdminInfo(adminBO);
        AdminVO adminVO = new AdminVO();
        BeanUtils.copyProperties(admin, adminVO);

        // TODO 4. 颁发jwtToken
        String adminToken = jwtUtils.createJWT(new Gson().toJson(adminVO), TOKEN_ADMIN_PREFIX);

        // TODO 5. 记录用户的token
        return GraceJSONResult.ok(adminToken);
    }

    /**
     * 运营平台获得admin信息
     *
     * @return
     */
    @GetMapping("info")
    public GraceJSONResult info() {

        // TODO 1. 通过本地线程获取admin用户
        Admin admin = JWTCurrentUserInterceptor.ADMIN_THREAD.get();

        AdminVO adminVO = new AdminVO();
        BeanUtils.copyProperties(admin, adminVO);
        // TODO 5. 记录用户的token
        return GraceJSONResult.ok(adminVO);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @PostMapping("logout")
    public GraceJSONResult logout() {
        return GraceJSONResult.ok();
    }
}






















